import { createStore } from 'vuex'
import storageUtil from '../utils/storage.js'

const store = createStore({
  state() {
    console.log('Store初始化开始...') // 调试日志

    const storedToken = storageUtil.getItem('token')
    const storedUser = storageUtil.getItem('user')

    console.log('从storage读取token:', storedToken) // 调试日志
    console.log('从storage读取user:', storedUser) // 调试日志

    const state = {
      token: storedToken || '',
      user: storedUser
    }

    console.log('Store初始化完成:', state) // 调试日志
    return state
  },
  mutations: {
    setToken(state, token) {
      console.log('setToken被调用，参数:', token) // 调试日志
      console.log('setToken调用前的state:', state) // 调试日志

      try {
        state.token = token
        console.log('state.token已更新:', state.token) // 调试日志

        const success = storageUtil.setItem('token', token)
        if (success) {
          console.log('token已保存到storage，验证:', storageUtil.getItem('token')) // 调试日志
        } else {
          console.error('token保存到storage失败')
        }
      } catch (e) {
        console.error('setToken执行失败:', e) // 调试日志
        throw e
      }
    },
    setUser(state, user) {
      console.log('setUser被调用，参数:', user) // 调试日志
      console.log('setUser调用前的state:', state) // 调试日志

      try {
        state.user = user
        console.log('state.user已更新:', state.user) // 调试日志

        const success = storageUtil.setItem('user', user)
        if (success) {
          console.log('user已保存到storage，验证:', storageUtil.getItem('user')) // 调试日志
        } else {
          console.error('user保存到storage失败')
        }
      } catch (e) {
        console.error('setUser执行失败:', e) // 调试日志
        throw e
      }
    },
    logout(state) {
      console.log('logout被调用') // 调试日志

      state.token = ''
      state.user = null
      storageUtil.removeItem('token')
      storageUtil.removeItem('user')

      console.log('logout执行完成') // 调试日志
    }
  },
  getters: {
    isLoggedIn: (state) => {
      return !!state.token
    }
  }
})

console.log('Store创建完成') // 调试日志

export default store
